import 'package:fish_redux/fish_redux.dart';
import 'package:www.znpigai.teacher/global_store/state.dart';
import 'package:www.znpigai.teacher/utils/http.dart';
import 'package:www.znpigai.teacher/utils/util.dart';

import 'action.dart';
import 'item/state.dart';
import 'state.dart';

Effect<PayTeacherListState> buildEffect() {
  return combineEffects(<Object, Effect<PayTeacherListState>>{
    Lifecycle.initState: _onReload,
    PayTeacherListAction.onLoad: _onLoad,
    PayTeacherListAction.onReload: _onReload,
  });
}

void _onReload(Action action, Context<PayTeacherListState> ctx) async {
  if (ctx.state.isLoading) {
    return;
  }

  if (action.payload != null) {
    action.payload(); // callback
  }

  _getPay(action, ctx, GlobalState.firstPageIndex, GlobalState.pageSize);
}

void _onLoad(Action action, Context<PayTeacherListState> ctx) async {
  var pageIndex = ctx.state.pageIndex;
  var total = ctx.state.pageTotal;
  var isLoading = ctx.state.isLoading;
  if (pageIndex >= total || isLoading) {
    return;
  }

  _getPay(action, ctx, pageIndex, GlobalState.pageSize);
}

void _getPay(Action action, Context<PayTeacherListState> ctx, int pageIndex,
    int pageSize) async {
  ctx.dispatch(PayTeacherListActionCreator.loading());

  var url = "/correct/pub/api/recharge/list.mvc";
  final query = {'cpage': pageIndex, 'psize': pageSize};
  var result = await Http.get(url, query: query);

  ctx.dispatch(PayTeacherListActionCreator.loaded());
  if (result.success) {
    var responseList = result.data;
    var pageTotal = 0;

    pageIndex += 1;
    List<PayTeacherState> items = new List();
    if (responseList != null) {
      responseList.forEach((item) {
        try {
          PayTeacherState cellData = new PayTeacherState.fromJson(item);
          items.add(cellData);
        } catch (e) {
          // No specified type, handles all
        }
      });
    }

    ctx.dispatch(
        PayTeacherListActionCreator.listResult(items, pageTotal, pageIndex));
  } else {
    Util.alertFail(result, ctx.context);
  }
}
